/**
 * 
 */
package com.wolfpire.workflow.controller;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.jbpm.api.ProcessEngine;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wolfpire.system.common.EasyuiPage;
import com.wolfpire.system.common.EasyuiPagination;
import com.wolfpire.system.common.Page;
import com.wolfpire.system.common.Result;
import com.wolfpire.system.common.springmvc.PrincipalArgument;
import com.wolfpire.system.model.User;
import com.wolfpire.workflow.om.ProInstance;
import com.wolfpire.workflow.om.Workflow;
import com.wolfpire.workflow.spring.DeployWorkFlowService;
import com.wolfpire.workflow.spring.WorkflowService;

/**
 * 流程定义管理控制器
 * @author lihd
 *
 */

@Controller
@RequestMapping("/workflow")
public class WorkflowController {
	
	@Resource private WorkflowService workflowService;
	
	@Resource private ProcessEngine processEngine;
	
	@Resource private DeployWorkFlowService deployWorkFlowService;
	
	@RequestMapping("/list")
	public ModelAndView list() {
		return new ModelAndView("workflow/workflow/workflow_list");
	}
	
	@ResponseBody
	@RequestMapping("/queryList")
	public EasyuiPagination<Workflow> queryList(EasyuiPage<Workflow> page, Workflow filterWorkflow) {
		Page<Workflow> workflows = this.workflowService.setPageDataList(page, filterWorkflow);
		return new EasyuiPagination<Workflow>(workflows);
	}
	
	/**
	 * 进入新增或编辑页面（流程设计器）
	 * @param wfTypeId 流程类型ID
	 * @param workflowId 流程定义ID
	 * @param wfVersionId 流程定义版本ID
	 * @return
	 */
	@RequestMapping(value = "/designer")
	public ModelAndView designer(
			@RequestParam(value = "wftypeId") String wftypeId,
			@RequestParam(value = "workFlowId", required = false) Long workFlowId,
			ModelMap map){
		map.put("wftypeId", wftypeId);
		map.put("workFlowId", workFlowId);
		return new ModelAndView("workflow/workflow/workflow_designer");
	}
	
	@ResponseBody
	@RequestMapping(value = "/save", method = {RequestMethod.GET, RequestMethod.POST}) 
	public Result save(HttpServletRequest request, Workflow workflow) {
		try {
			
			this.workflowService.saveOrUpdate(workflow);
			String rootPath = request.getSession().getServletContext().getRealPath("/");
			this.writeJPDL(rootPath + workflow.getFilePath(), workflow.getFlowXml());
			return new Result(true, "保存成功", workflow);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "保存失败");
		}
	}
	
	private void writeJPDL(String url, String content) throws Exception {
		
		FileChannel fc = new FileOutputStream(url).getChannel();
		fc.write(ByteBuffer.wrap(content.getBytes("UTF-8")));
		fc.close();
	}
	
	@ResponseBody
	@RequestMapping(value = "/flowXml")
	public String flowXml(Long workFlowId) {
		Workflow workflow = this.workflowService.get(workFlowId);
		return workflow.getFlowXml();
	}
	
	@ResponseBody
	@RequestMapping(value = "/deploy", method = {RequestMethod.GET, RequestMethod.POST}) 
	public Result deploy(HttpServletRequest request, Workflow workflow) {
		try {
			this.workflowService.saveOrUpdate(workflow);
			String rootPath = request.getSession().getServletContext().getRealPath("/");
			this.writeJPDL(rootPath + workflow.getFilePath(), workflow.getFlowXml());
			this.deployWorkFlowService.deployWorkFlow(this.processEngine.getRepositoryService(), workflow, rootPath);
			return new Result(true, "保存成功", workflow);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "保存失败");
		}
	}
	
	@RequestMapping(value = "/actorSelector", method = {RequestMethod.GET, RequestMethod.POST})
	public String actorSelector(
			@RequestParam(value = "actorIds", required = false) String actorIds,
			@RequestParam(value = "actorType", required = false) String actorType, 
			ModelMap modelMap){
		modelMap.put("actorIds", StringUtils.trimToEmpty(actorIds));
		modelMap.put("actorType", StringUtils.trimToEmpty(actorType));
		return "workflow/workflow/actor_selector";
	}
	
	@ResponseBody
	@RequestMapping("/testStart")
	public Result testStart(@PrincipalArgument User user,Workflow workflow) {
		try {
			Long formId = Long.valueOf(new Random().nextInt(100000));
			Map<String, Object> params = new HashMap<String, Object>();
			ProInstance proInstance = this.workflowService.startProcess(workflow.getWorkFlowId(), formId , user, params);
			
			return new Result(true, "启动成功," + proInstance.getInstanceId());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new Result(false, "启动失败");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/getFlowChart", method = {RequestMethod.GET, RequestMethod.POST})
	public Map<String, Object> getFlowChart(Long instanceId) throws DocumentException {
		return this.workflowService.getFlowChart(instanceId);
	}
	
	@ResponseBody
	@RequestMapping(value = "/workflows", method = {RequestMethod.GET, RequestMethod.POST})
	public List<Workflow> workflows(Workflow workflow) {
		return this.workflowService.list(workflow);
	}
}
